package com.zhiyou.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou.bean.*;
import com.zhiyou.service.*;
import com.zhiyou.util.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;

import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    CodeService codeService;

    @Autowired
    ProductService productService;

    @Autowired
    MyUtil myUtil;

    @Autowired
    UpmService upmService;

    @Autowired
    DianzanService dianzanService;

    @RequestMapping("/login")
    public String login(User user, HttpSession session) {
        User u = userService.getUser(user);
        System.out.println(u);
        if(u!=null){
            List<Upm> ul = upmService.getUpmsByUserId(u.getId());
            List<Product> pl = new ArrayList<>();
            for (Upm upm : ul){
                Product p = productService.getProductById(upm.getProductId());
                p.setPersonPayMoney(upm.getPayMoney());
                pl.add(p);
            }
            u.setUpmProductList(pl);

            List<Dianzan> dl = dianzanService.getDZByUserId(u.getId());
            List<Product> dzl = new ArrayList<>();
            for(Dianzan dz : dl){
                dzl.add(productService.getProductById(dz.getProductId()));
            }
            u.setDProductList(dzl);
        }
        session.setAttribute("user", u);
        return "redirect:/index.jsp";
    }

    @RequestMapping("/verify")
    @ResponseBody
    public int verify(Code code) {
        Code c = codeService.getCode(code);
        if (c == null) {
            return 0;
        }
        return 1;
    }

    @RequestMapping("/isRightTel")
    @ResponseBody
    public int isRightTel(String phone) {
        User u = userService.getUserByPhone(phone);
        return u == null ? 0 : 1;
    }

    @RequestMapping("/resetPwd")
    public String resetPwd(User user, Code code) {
        Code c = codeService.getCode(code);
        int i = userService.updateUserPwd(user);
        if (i > 0 && c != null) {
            return "redirect:/login.jsp";
        }
        return "redirect:/forgetPwd.jsp";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/index.jsp";
    }

    @RequestMapping("/identify")
    public String identify(User user, HttpSession session) {
        System.out.println("++++++++++++++++++iden+++++++++++++");
        User u = (User) session.getAttribute("user");
        u.setStatus(1);
        user.setId(u.getId());
        user.setStatus(1);
        int i = userService.identifyUser(user);
        return "redirect:/product/getByUserId";
    }


    //注册用户操作  获取全部用户 分页显示 每页显示6
    @RequestMapping("/getAllUser")
    public String getAllUser(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, HttpServletRequest request) {
        PageHelper.startPage(pageNo, 6);
        List<User> users = userService.getAllUser();
        PageInfo page = new PageInfo(users, 5);
        request.getSession().setAttribute("users", users);
        request.getSession().setAttribute("pageInfo", page);
        return "redirect:/admin/user/userInfo.jsp";
    }

    // 注册用户操作  根据id修改user信息
    @RequestMapping("/updateUserById")
    public String updateUserById(HttpServletRequest request) {
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        String status = request.getParameter("status");
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setUsername(username);
        user.setPassword(password);
        user.setStatus(Integer.parseInt(status));
        int i = userService.updateUserById(user);
        System.out.println("i===" + i);
        return "redirect:/admin/user/userInfo.jsp";
    }

    // 注册用户操作  根据id删除user信息
    @RequestMapping("/deleteUserById")
    @ResponseBody
    public String deleteUserById(Integer id) {
        System.out.println("id=" + id);
        int i = userService.deleteUserById(id);
        System.out.println("i=" + i);
        return "redirect:/admin/user/userInfo.jsp";
    }

    //注册用户操作 根据名字模糊查询
    @RequestMapping("/getUserByName")
    public String getUserByName(HttpServletRequest request) {
        String username = request.getParameter("username");
        System.out.println("name=" + username);
        List<User> users = userService.getUserByName(username);
        users.stream().forEach(user -> {
            System.out.println("user=" + user);
        });
        request.getSession().setAttribute("users", users);
        return "redirect:/admin/user/userInfo.jsp";
    }

    // 用户资金  项目和用户连表查
    @RequestMapping("/getUserMoney")
    public String getUserMoney(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, HttpServletRequest request) {
        PageHelper.startPage(pageNo, 6);
        List<Product> products = userService.getUserMoney();
        PageInfo page = new PageInfo(products, 5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo", page);
        return "redirect:/admin/user/userMoney.jsp";
    }

    // 用户资金  用户名字模糊查询 项目和用户连表查
    @RequestMapping("/getUserAndProductByName")
    public String getUserAndProductByName(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, HttpServletRequest request) {
        PageHelper.startPage(pageNo, 6);
        String username = request.getParameter("username");
        List<Product> products = userService.getUserAndProductByName(username);
        PageInfo page = new PageInfo(products, 5);
        request.getSession().setAttribute("products", products);
        request.getSession().setAttribute("pageInfo", page);
        return "redirect:/admin/user/userMoney.jsp";
    }

    //用户资金  根据项目id删除 删除总金额 筹资金额
    @RequestMapping("/deleteUserAndProductById")
    public String deleteUserAndProductById(Integer id) {
        System.out.println("id=" + id);
        int i = productService.deleteUserAndProductById(id);
        System.out.println("i=" + i);
        return "redirect:/admin/user/userMoney.jsp";
    }

    // 用户日志  记录用户行为 登录 添加 删除 修改

    //获取全部用户审核 分页显示 每页显示6  只查询审核中的数据
    @RequestMapping("/getAllUserAudit")
    public String getAllUserAudit(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, HttpServletRequest request) {
        PageHelper.startPage(pageNo, 6);
        List<User> users = userService.getAllUserAudit(1);
        PageInfo page = new PageInfo(users, 5);
        request.getSession().setAttribute("users", users);
        request.getSession().setAttribute("pageInfo", page);
        return "redirect:/admin/user/userAudit.jsp";
    }

    //用户审核  用户名字模糊查询
    @RequestMapping("/getUserByNameAudit")
    public String getUserByNameAudit(HttpServletRequest request) {
        String realname = request.getParameter("realname");
        List<User> users = userService.getUserByNameAudit(realname, 1);
        request.getSession().setAttribute("users", users);
        return "redirect:/admin/user/userAudit.jsp";
    }

    //todo 用户审核 实名审核
    // 只能操作审核中这个操作 出现两种结果 失败 成功  可以成功 但是前端不跳提示消息
    //只做了长度判断
    @ResponseBody
    @RequestMapping("/auditUser")
    public String auditUser(@Param("id") String id, @Param("idCard") String idCard) {
        System.out.println("id=" + id + "idCard===" + idCard);
        //正则表达式
        ///^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/; 15位身份证
        ///^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9xX]$/;18位
        if (idCard.length() == 18) {
            System.out.println("=============");
            int status = 2;
            int i = userService.auditUser(Integer.parseInt(id), status);
            System.out.println(i + "-----");
            if (i > 0) {
                return "success";
            } else {
                return "fail";
            }
        } else {
            //状态 3
            int status = 3;
            int i = userService.auditUser(Integer.parseInt(id), status);
            System.out.println(i + "======");
            if (i > 0) {
                return "success";
            } else {
                return "fail";
            }
        }
    }

    //注册
    @RequestMapping(value = "/zhuce", method = RequestMethod.GET)
    public String getAll(String email,String username, String password,String upassword
            , HttpServletRequest request, HttpServletResponse response) {
//        1.加入校验
        System.out.println("============================");
        System.out.println("email = " + email);
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        System.out.println("upassword = " + upassword);
        if ("".equals(email) || email == null || "".equals(password) || password == null|| "".equals(upassword) || upassword == null|| "".equals(username) || username == null) {
            request.setAttribute("errMsg", "用户名或密码不能为空！");
            return "reg";
        }
        if (!upassword.equals(password)){
            request.setAttribute("errMsg", "两次输入的密码不一致！");
            return "reg";
        }
        try {
            int i = 0;
            if (email.contains("@qq.com")||email.contains("@QQ.com")){
                if (userService.emailchachong(email).size()==0){
                    if (userService.zhuceEmail(email,username, password)!=0) {//邮箱注册
                        i = 1;
                    }else {
                        request.setAttribute("errMsg", "邮箱不符合规范！！");
                        return "reg";
                    }
                }else {
                    request.setAttribute("errMsg", "邮箱已存在！！");
                    return "reg";
                }
            }else {
                if (email.length()==11){
                    if (userService.usernamechachong(username).size()!=0
                            ||userService.phonechachong(email).size()!=0){
                        request.setAttribute("errMsg", "用户名或者手机号已存在！！");
                        return "reg";
                    }else {
                        if (userService.ZhucePhone(email,username, password)!=0) {//手机号注册
                            i = 1;
                            System.out.println("i = " + i);
                        }
                    }
                }else {
                    request.setAttribute("errMsg", "手机号不符合验证！！");
                    return "reg";
                }
                System.out.println("i = " + i);
            }
            if (i!=0) {
                request.getSession().setAttribute("user",i);
                return "redirect:/login.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("errMsg","用户名重复！！");
        return "reg";
    }

}
